﻿#include "PreciseTimer.h"

namespace Common {

	PreciseTimer::PreciseTimer()
		: m_thread(nullptr)
		, m_isExit(false)
	{

	}

	PreciseTimer::~PreciseTimer()
	{
		stop();
	}

	void PreciseTimer::start(int msec)
	{
		if (m_thread)
		{
			m_isExit = true;
			m_thread->join();
			delete m_thread;
			m_thread = nullptr;
		}

		m_isExit = false;
		m_sleepTime = msec;
		m_thread = new std::thread(threadFunc, this);
	}

	void PreciseTimer::stop()
	{
		m_isExit = true;
		if (m_thread)
		{
			m_thread->join();
			delete m_thread;
			m_thread = nullptr;
		}
	}

	void PreciseTimer::threadFunc(void * arg)
	{
		PreciseTimer* pool = (PreciseTimer *)arg;
		while (!pool->m_isExit)
		{
			std::this_thread::sleep_for(std::chrono::milliseconds(pool->m_sleepTime));
			emit pool->signalTimeout();
		}
	}

}
